import { Show, createMemo } from "solid-js"
import { createStore } from "solid-js/store"
import { createAsync, useParams, useAction, useSubmission } from "@solidjs/router"
import { NewUserSection } from "./new-user-section"
import { ModelSection } from "./model-section"
import { ProviderSection } from "./provider-section"
import { IconZen } from "~/component/icon"
import { querySessionInfo, queryBillingInfo, createCheckoutUrl, formatBalance } from "../common"
import { useI18n } from "~/context/i18n"
import { useLanguage } from "~/context/language"

export default function () {
  const params = useParams()
  const i18n = useI18n()
  const language = useLanguage()
  const userInfo = createAsync(() => querySessionInfo(params.id!))
  const billingInfo = createAsync(() => queryBillingInfo(params.id!))
  const checkoutAction = useAction(createCheckoutUrl)
  const checkoutSubmission = useSubmission(createCheckoutUrl)
  const [store, setStore] = createStore({
    checkoutRedirecting: false,
  })
  const balance = createMemo(() => formatBalance(billingInfo()?.balance ?? 0))

  async function onClickCheckout() {
    const baseUrl = window.location.href
    const checkout = await checkoutAction(params.id!, billingInfo()!.reloadAmount, baseUrl, baseUrl)
    if (checkout && checkout.data) {
      setStore("checkoutRedirecting", true)
      window.location.href = checkout.data
    }
  }

  return (
    <div data-page="workspace-[id]">
      <section data-component="header-section">
        <IconZen />
        <p>
          <span>
            {i18n.t("workspace.home.banner.beforeLink")}{" "}
            <a target="_blank" href={language.route("/docs/zen")}>
              {i18n.t("common.learnMore")}
            </a>
            .
          </span>
          <Show when={userInfo()?.isAdmin}>
            <span data-slot="billing-info">
              <Show
                when={billingInfo()?.customerID}
                fallback={
                  <button
                    data-color="primary"
                    data-size="sm"
                    disabled={checkoutSubmission.pending || store.checkoutRedirecting}
                    onClick={onClickCheckout}
                  >
                    {checkoutSubmission.pending || store.checkoutRedirecting
                      ? i18n.t("workspace.home.billing.loading")
                      : i18n.t("workspace.home.billing.enable")}
                  </button>
                }
              >
                <span data-slot="balance">
                  {i18n.t("workspace.home.billing.currentBalance")} <b>${balance()}</b>
                </span>
              </Show>
            </span>
          </Show>
        </p>
      </section>

      <div data-slot="sections">
        <NewUserSection />
        <ModelSection />
        <Show when={userInfo()?.isAdmin}>
          <ProviderSection />
        </Show>
      </div>
    </div>
  )
}
